package com.cloud.sample.consumer.core.http;

import com.cloud.sample.consumer.core.constant.ConsumerConstants;
import org.springframework.http.HttpStatus;

import java.util.List;

/**
 * @author gjy
 * @since 2021/7/1 0001
 */
public class ApiListResponse<T> extends BaseResponse {

    protected List<T> rows;

    public ApiListResponse(String message) {
        super(message);
    }

    public ApiListResponse(Integer code, String message) {
        super(code, message);
    }

    public ApiListResponse(Integer code, String message, Integer errorCode) {
        super(code, message, errorCode);
    }

    public ApiListResponse(Integer code, String message, Integer errorCode, List<T> rows) {
        super(code, message, errorCode);
        this.rows = rows;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public boolean isError() {
        return this.errorCode != null;
    }

    @Override
    public String toString() {
        return "ApiResponse{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", errorCode=" + errorCode +
                ", rows=" + rows +
                '}';
    }

    public static class Builder {
        public static <T> ApiListResponse<T> ok() {
            return ok(null);
        }

        public static <T> ApiListResponse<T> ok(List<T> rows) {
            return ok(ConsumerConstants.SUCCESS, rows);
        }

        public static <T> ApiListResponse<T> ok(String message, List<T> rows) {
            return build(HttpStatus.OK.value(), message, null, rows);
        }


        public static <T> ApiListResponse<T> fail() {
            return fail(ConsumerConstants.FAIL);
        }

        public static <T> ApiListResponse<T> fail(String message) {
            return build(HttpStatus.INSUFFICIENT_STORAGE.value(), message, null, null);
        }

        public static <T> ApiListResponse<T> fail(Integer errorCode, String message) {
            return build(HttpStatus.INSUFFICIENT_STORAGE.value(), message, errorCode, null);
        }

        private static <T> ApiListResponse<T> build(Integer code, String message, Integer errorCode, List<T> rows) {
            return new ApiListResponse<T>(code, message, errorCode, rows);
        }

    }
}
